document.addEventListener('DOMContentLoaded', function() {
  const shortcutElements = document.querySelectorAll('.shortcut-key');
  
  // 获取快捷键设置
  chrome.storage.local.get(['dialogShortcut', 'exploreShortcut'], function(result) {
    const exploreKey = result.exploreShortcut || 'Ctrl+Shift+E';
    const dialogKey = result.dialogShortcut || 'Ctrl+Shift+Y';
    
    shortcutElements[0].textContent = `${exploreKey}: 探索`;
    shortcutElements[1].textContent = `${dialogKey}: 对话`;
  });

  // 监听快捷键变化
  chrome.storage.onChanged.addListener(function(changes, namespace) {
    if (namespace === 'local') {
      if (changes.exploreShortcut) {
        shortcutElements[0].textContent = `${changes.exploreShortcut.newValue || 'Ctrl+Shift+E'}: 探索`;
      }
      if (changes.dialogShortcut) {
        shortcutElements[1].textContent = `${changes.dialogShortcut.newValue || 'Ctrl+Shift+Y'}: 对话`;
      }
    }
  });

  // 访问YinliAI按钮点击事件
  document.querySelector('.visit-kimi').addEventListener('click', function() {
    chrome.tabs.create({ url: 'https://ai.yinlimedia.com/creative/assistant/douyin' });
  });

  const input = document.querySelector('.chat-input');
  const sendButton = document.querySelector('.chat-send-button');
  const contentDiv = document.querySelector('.chat-content');

  // 发送消息
  async function sendMessage(question) {
    if (!question.trim()) return;

    // 添加用户消息
    addMessage(question, true);
    input.value = '';

    try {
      const response = await sendChatRequest(question);
      let fullText = '';
      
      for await (const chunk of streamResponse(response)) {
        fullText = chunk;
        const messageContent = document.querySelector('.ai.chat-message:last-child .message-content');
        if (messageContent) {
          messageContent.innerHTML = renderMarkdown(fullText);
          contentDiv.scrollTop = contentDiv.scrollHeight;
        }
      }
    } catch (error) {
      addMessage("抱歉，请求失败，请重试。", false);
    }
  }

  // 发送按钮点击事件
  sendButton.addEventListener('click', () => {
    sendMessage(input.value);
  });

  // 回车发送
  input.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage(input.value);
    }
  });
}); 